package com.haifeng.mywriteaidldemo.MyAIDL;

import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;

/**
 * 创建远程服务代理类 其主要功能是对客户端提交的参数进行的封装
 */
public class Proxy implements MyInterface {

    private static final String DESCRIPTOR = "com.haifeng.mywriteaidldemo.MyInterface";

    static MyInterface minterface;

    IBinder iBinder;

    Proxy(IBinder remots) {
        this.iBinder = remots;
    }

    @Override
    public IBinder asBinder() {
        return iBinder;
    }

    @Override
    public void addname(String position) throws RuntimeException {
        Parcel _data = Parcel.obtain();
        Parcel _reply = Parcel.obtain();
        String _result;
        boolean _state = false;
        try {
            _data.writeInterfaceToken(DESCRIPTOR);
            //对参数进行封装
            _data.writeString(position);
            //主要为调用服务端接口
            _state = iBinder.transact(Stub.TRANCACTION_ADDNAME, _data, _reply, 0);

//            if (!_state&&minterface!=null){
//                minterface.addname(position);
//            }
//
            _reply.readException();
        } catch (RemoteException | RuntimeException e) {
            e.printStackTrace();
        } finally {
            _data.recycle();
            _reply.recycle();
        }
    }

    @Override
    public String getname(String key) throws RuntimeException {
        Parcel _data = Parcel.obtain();
        Parcel _reply = Parcel.obtain();
        String _result = null;
        boolean _state = false;
        try {
            _data.writeInterfaceToken(DESCRIPTOR);
            _data.writeString(key);
            _state = iBinder.transact(Stub.TRANCACTION_GETNAME, _data, _reply, 0);
//            if (!_state&&minterface!=null){
//            return minterface.getname(key);
//            }
            _reply.readException();
            _result = _reply.readString();
        } catch (RemoteException e) {
            e.printStackTrace();
        } finally {
            _data.recycle();
            _reply.recycle();
        }
        return _result;
    }
}
